import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: null,
    token: null
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    SET_TOKEN(state, token) {
      state.token = token
    },
    CLEAR_USER(state) {
      state.user = null
      state.token = null
    }
  },
  actions: {
    login({ commit }, { user, token }) {
      commit('SET_USER', user)
      commit('SET_TOKEN', token)
      localStorage.setItem('user', JSON.stringify(user))
      localStorage.setItem('token', token)
    },
    logout({ commit }) {
      commit('CLEAR_USER')
      localStorage.removeItem('user')
      localStorage.removeItem('token')
    },
    initializeStore({ commit }) {
      const user = localStorage.getItem('user')
      const token = localStorage.getItem('token')
      if (user && token) {
        commit('SET_USER', JSON.parse(user))
        commit('SET_TOKEN', token)
      }
    }
  },
  getters: {
    isLoggedIn: state => !!state.token,
    userRole: state => state.user?.role,
    username: state => state.user?.username
  }
})
